package com.example.connection.ui.chat;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.connection.MainActivity;
import com.example.connection.R;
import com.example.connection.databinding.ChatFragmentBinding;
import com.example.connection.databinding.FragmentConnBinding;
import com.example.connection.databinding.FragmentSlideshowBinding;
import com.example.connection.ui.slideshow.SlideshowViewModel;

public class ChatFragment extends Fragment {

    private ChatViewModel mViewModel;
    private ChatFragmentBinding binding;
    public static ChatFragment newInstance() {
        return new ChatFragment();
    }
    MainActivity activity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mViewModel = new ViewModelProvider(this).get(ChatViewModel.class);
        binding = ChatFragmentBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        final TextView textView = binding.historyInfo;
        final EditText currentinfo =binding.currentInfo;
        final Button sendButton=binding.sendButton;
        mViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.sendMSG(currentinfo.getText().toString());
            }
        });
        activity.notifyLiveData.observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
            String info = textView.getText()+s;
                textView.setText(info);

            }
        });
        return root;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(ChatViewModel.class);
        // TODO: Use the ViewModel
    }

}